package com.ng.desktop.hr.view.customer;

import javax.swing.JOptionPane;

import com.ng.desktop.hr.model.Customer;
import com.ng.desktop.hr.model.Email;
import com.ng.desktop.hr.model.Phone;
import com.ng.desktop.hr.model.Tag;
import com.ng.desktop.hr.persistence.CustomerPersistence;
import com.ng.framework.view.desktop.NGEntitySelectorField;
import com.ng.framework.view.desktop.NGTablePanel;

public class CustomerTablePanel extends NGTablePanel<Customer, CustomerPersistence> {

	private NGEntitySelectorField<Customer,CustomerPersistence> entitySelection;

	public CustomerTablePanel(CustomerPersistence persistence) {
		super(persistence);
	}

	public CustomerTablePanel(CustomerPersistence persistence, NGEntitySelectorField<Customer,CustomerPersistence> entitySelection) {
		super(persistence, entitySelection);
		this.entitySelection = entitySelection;
	}

	private static final long serialVersionUID = -3041915458364809210L;

	private static final String[] COLUMN_NAMES = {"Id", "Nombre", "Apellido", "Email", "Teléfono", "!!", "Etiquetas"};

	// 45 menos que el width

	private static final int[] COLUMN_WIDTHS = {50, 200, 200, 200, 200, 50, 79};

	@Override
	protected String[] getColumnNames() {
		return COLUMN_NAMES;
	}

	@Override
	protected int[] getColumnWidths() {
		return COLUMN_WIDTHS;
	}

	@Override
	protected Object[] toRow(Customer instance) {
		String emailLiteral = "";
		for (Email email : instance.getEmails()) {
			if (email.getPrimaryUse()) {
				emailLiteral = email.getLiteral();
			}
		}

		String phoneLiteral = "";
		for (Phone phone : instance.getPhones()) {
			if (phone.getPrimaryUse()) {
				phoneLiteral = phone.getNumber();
			}
		}

		StringBuilder tags = new StringBuilder();

		for (Tag tag : instance.getTags()) {
			tags.append("-" + tag.getFullName());
		}

		return new Object[]{instance.getId(), instance.getName(), instance.getLastName(), emailLiteral, phoneLiteral,
				instance.getPending() != null && instance.getPending().equals(Boolean.TRUE) ? "SI" : "NO", tags.toString()};

	}

	@Override
	protected boolean create(CustomerPersistence persistence) {
		CustomerEditDialog dialog = new CustomerEditDialog(JOptionPane.getFrameForComponent(this), persistence, entitySelection);
		dialog.setLocationRelativeTo(this);
		dialog.setVisible(true);
		return true;
	}

	@Override
	protected boolean edit(CustomerPersistence persistence, Customer instance) {
		CustomerEditDialog dialog = new CustomerEditDialog(JOptionPane.getFrameForComponent(this), persistence, instance,
				entitySelection);
		dialog.setLocationRelativeTo(this);
		dialog.setVisible(true);
		return true;
	}

	@Override
	protected Customer getSelectedInstance(CustomerPersistence persistence, Object[] rowData) {
		return persistence.findById((Long) rowData[0]);
	}
}
